package com.ruoyi.merchant.utils;

import com.ruoyi.merchant.domain.Order;
import com.ruoyi.merchant.domain.OrderItem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 订单Excel导出工具
 */
public class OrderExcelUtil {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 导出订单列表
     */
    public static byte[] exportOrders(List<Order> orders) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("订单列表");

        // 创建标题行样式
        CellStyle headerStyle = createHeaderStyle(workbook);
        CellStyle dataStyle = createDataStyle(workbook);

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {
            "订单号", "取餐码", "订单状态", "支付方式", "支付状态",
            "商品总额", "优惠金额", "实付金额", "备注", "下单时间"
        };
        
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        // 填充数据
        int rowNum = 1;
        for (Order order : orders) {
            Row row = sheet.createRow(rowNum++);
            
            createCell(row, 0, order.getOrderNo(), dataStyle);
            createCell(row, 1, order.getPickupCode(), dataStyle);
            createCell(row, 2, getStatusText(order.getStatus()), dataStyle);
            createCell(row, 3, getPaymentMethodText(order.getPaymentMethod()), dataStyle);
            createCell(row, 4, getPaymentStatusText(order.getPaymentStatus()), dataStyle);
            createCell(row, 5, order.getTotalAmount().toString(), dataStyle);
            createCell(row, 6, order.getDiscountAmount().toString(), dataStyle);
            createCell(row, 7, order.getFinalAmount().toString(), dataStyle);
            createCell(row, 8, order.getRemark(), dataStyle);
            createCell(row, 9, DATE_FORMAT.format(order.getCreatedAt()), dataStyle);
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) + 1000);
        }

        // 输出到字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();
        
        return outputStream.toByteArray();
    }

    /**
     * 导出订单详情（包含商品明细）
     */
    public static byte[] exportOrderDetail(Order order) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        
        // 订单基本信息
        Sheet infoSheet = workbook.createSheet("订单信息");
        CellStyle headerStyle = createHeaderStyle(workbook);
        CellStyle dataStyle = createDataStyle(workbook);

        int rowNum = 0;
        
        // 订单号
        Row row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "订单号", headerStyle);
        createCell(row, 1, order.getOrderNo(), dataStyle);

        // 取餐码
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "取餐码", headerStyle);
        createCell(row, 1, order.getPickupCode(), dataStyle);

        // 订单状态
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "订单状态", headerStyle);
        createCell(row, 1, getStatusText(order.getStatus()), dataStyle);

        // 商品总额
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "商品总额", headerStyle);
        createCell(row, 1, "¥" + order.getTotalAmount(), dataStyle);

        // 优惠金额
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "优惠金额", headerStyle);
        createCell(row, 1, "¥" + order.getDiscountAmount(), dataStyle);

        // 实付金额
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "实付金额", headerStyle);
        createCell(row, 1, "¥" + order.getFinalAmount(), dataStyle);

        // 支付方式
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "支付方式", headerStyle);
        createCell(row, 1, getPaymentMethodText(order.getPaymentMethod()), dataStyle);

        // 备注
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "备注", headerStyle);
        createCell(row, 1, order.getRemark(), dataStyle);

        // 下单时间
        row = infoSheet.createRow(rowNum++);
        createCell(row, 0, "下单时间", headerStyle);
        createCell(row, 1, DATE_FORMAT.format(order.getCreatedAt()), dataStyle);

        // 调整列宽
        infoSheet.setColumnWidth(0, 4000);
        infoSheet.setColumnWidth(1, 8000);

        // 商品明细
        Sheet itemsSheet = workbook.createSheet("商品明细");
        Row headerRow = itemsSheet.createRow(0);
        String[] headers = {"商品名称", "数量", "单价", "小计"};
        
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        int itemRowNum = 1;
        for (OrderItem item : order.getItems()) {
            Row itemRow = itemsSheet.createRow(itemRowNum++);
            createCell(itemRow, 0, item.getProductName(), dataStyle);
            createCell(itemRow, 1, String.valueOf(item.getQuantity()), dataStyle);
            createCell(itemRow, 2, "¥" + item.getUnitPrice(), dataStyle);
            createCell(itemRow, 3, "¥" + item.getTotalPrice(), dataStyle);
        }

        // 调整列宽
        for (int i = 0; i < headers.length; i++) {
            itemsSheet.autoSizeColumn(i);
            itemsSheet.setColumnWidth(i, itemsSheet.getColumnWidth(i) + 1000);
        }

        // 输出到字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();
        
        return outputStream.toByteArray();
    }

    /**
     * 创建单元格
     */
    private static void createCell(Row row, int column, String value, CellStyle style) {
        Cell cell = row.createCell(column);
        cell.setCellValue(value == null ? "" : value);
        cell.setCellStyle(style);
    }

    /**
     * 创建标题样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 11);
        style.setFont(font);
        
        return style;
    }

    /**
     * 创建数据样式
     */
    private static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 10);
        style.setFont(font);
        
        return style;
    }

    /**
     * 获取状态文本
     */
    private static String getStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "待接单";
            case 1: return "已接单";
            case 2: return "制作中";
            case 3: return "待取餐";
            case 4: return "已完成";
            case 5: return "已取消";
            default: return "未知";
        }
    }

    /**
     * 获取支付方式文本
     */
    private static String getPaymentMethodText(Integer method) {
        if (method == null) return "";
        switch (method) {
            case 1: return "微信支付";
            case 2: return "余额支付";
            default: return "未知";
        }
    }

    /**
     * 获取支付状态文本
     */
    private static String getPaymentStatusText(Integer status) {
        if (status == null) return "";
        switch (status) {
            case 0: return "未支付";
            case 1: return "已支付";
            case 2: return "已退款";
            default: return "未知";
        }
    }
}
